package org.ants.basecomponent.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.ants.basecomponent.config.Globals;
import org.ants.basecomponent.entity.user.SysUser;
import org.ants.basecomponent.service.user.SysUserService;
import org.ants.basecomponent.session.UserInfo;
import org.ants.tinymvc.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.tinygroup.commons.tools.StringUtil;

@Controller
@RequestMapping("{ANTS_ADMIN_PATH}")
public class LoginController extends BaseController {

	@Autowired
	private SysUserService sysUserService;

	@RequestMapping("")
	public String execute() {
		return Globals.getDefaultViewsPath()+"/system/login";
	}

	@RequestMapping("/redirect")
	public String redirectLogin() {
		return "/login_redirect";
	}

	@RequestMapping("/login")
	@ResponseBody
	public Map<?, ?> login(HttpSession session, String userId, String userPwd)
			throws Exception {
		String msg = "用户名或密码错误！";
		int status = 0;
		if (!StringUtil.isEmpty(userId) && !StringUtil.isEmpty(userPwd)) {
			SysUser sysUser = this.sysUserService.login(userId, userPwd);
			if (sysUser != null) {
				UserInfo userInfo = new UserInfo();
				userInfo.setUserName(userId);
				msg = "登录成功!";
				session.setAttribute("userInfo", userInfo);
				status = 1;
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("status", status);
		map.put("info", msg);
		return map;
	}

	@RequestMapping("/logout")
	public String logout(HttpSession session, HttpServletRequest request) {
		session.removeAttribute("userInfo");
		session.invalidate();
		return "redirect:/";

	}
}
